﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ChatData;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using System.Data.Services.Client;

namespace WCFServiceWebRole1
{
    public class DMDataSource
    {
        private DMDataServiceContext _ServiceContext = null;

       
        public DMDataSource(CloudStorageAccount storageAccount)
        {
            // var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            _ServiceContext = new DMDataServiceContext(storageAccount.TableEndpoint.ToString(), storageAccount.Credentials);

            // Create the tables
            // In this case, just a single table.  
            storageAccount.CreateCloudTableClient().CreateTableIfNotExist(DMDataServiceContext.DMTableName);
        }

        public IEnumerable<DMDataModel> Select()
        {
            var results = (from c in _ServiceContext.DMTable
                           select c);

            var query = results.AsTableServiceQuery<DMDataModel>();
            var queryResults = query.Execute();

            return queryResults;
        }


        public IEnumerable<DMDataModel> getUserStream(string username)
        {
            var results = (from c in _ServiceContext.DMTable
                           where c.UserName==username
                           select c).Take(100);

            var query = results.AsTableServiceQuery<DMDataModel>();
            var queryResults = query.Execute();

            return queryResults;
        }

        public IEnumerable<DMDataModel> getUserStreamSince(string username, DateTime dateTime)
        {
            var results = (from c in _ServiceContext.DMTable
                           where c.Time.isLaterThan(dateTime)
                           select c).Take(100);

            var query = results.AsTableServiceQuery<DMDataModel>();
            var queryResults = query.Execute();

            return queryResults;
        }

        public void Insert(DMDataModel thedm)
        {
            _ServiceContext.UpdateObject(thedm);
            _ServiceContext.SaveChanges();
        }
    }
}
